package com.spring.cloud.eurekaclientzuul.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Repository
public class RouteDaoImpl implements RouteDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //查询的SQL
    private final static String QUERY_SQL =
            "select id,path,service_id,url,enable,retryable from zuul_routes "
            + "where enable = true";


    @Override
    public Map<String, ZuulProperties.ZuulRoute> findEnableRoutes() {

        //结果map
        Map<String,ZuulProperties.ZuulRoute> routeMap = new LinkedHashMap<>();

        jdbcTemplate.query(QUERY_SQL,(ResultSet rs, int index)->{
            ZuulProperties.ZuulRoute zuulRoute = new ZuulProperties.ZuulRoute();
            try{
                String id = rs.getLong("id")+"";
                String path = rs.getString("path");
                String serviceId = rs.getString("service_id");
                String url = rs.getString("url");
                Boolean retryable = rs.getBoolean("retryable");

                //构建值为zuulRoute对象
                zuulRoute.setId(id);
                zuulRoute.setPath(path);
                zuulRoute.setServiceId(serviceId);
                zuulRoute.setUrl(url);
                zuulRoute.setRetryable(retryable);
                //是否带前缀
                zuulRoute.setStripPrefix(true);

                //key为path,值为zuulRoute类型
                routeMap.put(path,zuulRoute);

            }catch (Exception ex){
                ex.printStackTrace();
            }
            return zuulRoute;
        });

        return routeMap;
    }
}
